package com.zlp.partice.io.biochat;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: zhulaiping
 * @time: 2022/8/8 15:53
 */
public class BioDemo2_Chat {


    static List<Socket> socketList = new ArrayList<>();
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        ExecutorService executorService =
                new ThreadPoolExecutor(3,3,120, TimeUnit.SECONDS,new ArrayBlockingQueue<>(10));
        while (true){
            Socket socket = serverSocket.accept();
            socketList.add(socket);
            Runnable task = new ServerRunnable2(socket);
            executorService.execute(task);
        }
    }

    static class ServerRunnable2 implements Runnable{

        private Socket socket;


        public ServerRunnable2(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            try {

                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String msg;
                //PrintStream ps = new PrintStream(socket.getOutputStream());
                while ((msg = br.readLine()) != null){
                    sendMessage(msg);
                }
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("下线");
                BioDemo2_Chat.socketList.remove(socket);
            }

        }

        private void sendMessage(String msg) throws IOException {
            for (Socket socket:BioDemo2_Chat.socketList){
                if(socket == this.socket) continue;
                PrintStream ps = new PrintStream(socket.getOutputStream());
                ps.println(msg);
            }
        }
    }
}
